<template>
  <div class="app-container">
    <div style="display: flex; align-items: center;">
      <el-space>
        <el-button type="primary" @click="handleBack">返回</el-button>
        <div style="font-size: 20px; font-weight: bold">发布商品</div>
      </el-space>
      <el-space style="margin-left: auto;">
        <el-space spacer=" ">
          <el-text>是否覆盖已发布商品 </el-text>
          <el-radio-group v-model="productRelease.covered">
            <el-radio :value="false" size="large">不覆盖</el-radio>
            <el-radio :value="true" size="large">覆盖</el-radio>
          </el-radio-group>
        </el-space>

        <el-space spacer=" " style="margin: 0 50px;">
          <el-text>上架设置 </el-text>
          <el-radio-group v-model="productRelease.publishAfterStatus">
            <el-radio value="Waiting" size="large">发布后暂不上架</el-radio>
            <el-radio value="Temporary" size="large">发布后直接上架</el-radio>
          </el-radio-group>
        </el-space>
        <el-space style=" margin-left: auto;">
          <el-text v-if="siteLength">已选择{{ siteLength }}个站点</el-text>
          <el-button type="primary" @click="choseSite" style="margin-right: 20px">选择站点</el-button>
          <el-button type="primary" @click="handleRelease">发布商品</el-button>
        </el-space>
      </el-space>
    </div>


    <el-table border :data="productList" style="margin: 20px 0; height: calc(100vh - 300px)">
      <el-table-column label="ID" align="center" prop="id" width="100" />
      <el-table-column label="商品图" align="center" prop="newImage" width="200">
        <template #default="scope">
          <image-preview :src="scope.row.newImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="商品类型" align="center" prop="productCategoryFullName" />
      <el-table-column label="商品名称" prop="productName" />
      <el-table-column label="来源网站" align="center" prop="collectionSiteName" />
      <el-table-column label="操作" align="center" width="100" fixed="right">
        <template #default="scope">
          <el-button link type="danger" @click="handleDelete(scope.row, scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination :total="total" :limit="queryParams.pageSize" :page="queryParams.pageNum" @pagination="handlePageChange">
    </Pagination>

    <publicSite :dialogVisible="dialogVisible" :newType="false" @handleListClose="handleListClose"
      @handleListSure="handleListSure" :listItem="productRelease"></publicSite>
  </div>
</template>

<script setup name="ProductPublish">
import publicSite from "@/views/publicSite";
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";

const route = useRoute();
const router = useRouter();
const dialogVisible = ref(false);
const { proxy } = getCurrentInstance();
const total = ref(0);
const siteLength = ref(0);

const productList = ref([]);
const productRelease = ref({
  productIds: [],
  websiteIds: [],
  covered: false,//是否选择覆盖
  publishAfterStatus: "Waiting",//Waiting等待，Temporary直接上架
  // forced: null//是否选择强制覆盖

}); //发布产品参数

const queryParams = ref({
  pageNum: 1,
  pageSize: 100,
  param: {
    productIds: [], //产品名称
  },
});

onMounted(() => {
  getList();
});
const getList = () => {
  let newListIds = JSON.parse(sessionStorage.getItem("productListIds"));
  if (Array.isArray(newListIds) && newListIds.length) {
    queryParams.value.param.productIds = newListIds;
  } else {
    handleBack();
    proxy.$modal.msgWarning("请在产品中心重新勾选");
    return;
  }
  product.general
    .productGettobepublishedproductlist({
      data: queryParams.value,
    })
    .then((res) => {
      total.value = res.total;
      if (res.data?.length) {
        res.data = res.data.map((e) => {
          return {
            ...e,
            newImage: handleImage(e),
          };
        });
      }
      productList.value = res.data;
    });
};
// 删除
const handleDelete = (rowItem, index) => {
  proxy.$modal.confirm("是否确认删除此数据？").then(() => {
    var newListIds = JSON.parse(sessionStorage.getItem("productListIds"));
    var ids = newListIds.findIndex((e) => e === rowItem.id);
    newListIds.splice(ids, 1);
    sessionStorage.setItem("productListIds", JSON.stringify(newListIds));
    delete productList.value[index];
    total.value = total.value - 1;
    if (!total.value) return getList();
  });
};
// 发布商品
const handleRelease = () => {
  let newListIds = JSON.parse(sessionStorage.getItem("productListIds"));
  if (!productRelease.value.websiteIds.length)
    return proxy.$modal.msgWarning("请选择发布的站点");
  productRelease.value.productIds = newListIds;
  proxy.$modal.confirm("是否确认发布商品？").then(() => {
    product.personalproduct.personalproductPublish({
      data: productRelease.value
    }
    ).then((res) => {
      if (res.code === 200 && res.data.logStatus === 'Succeed') {
        proxy.$modal.msgSuccess(res.message);
        handleBack();
      } else {
        LoseError(res);
      }
    });
  });
};
const LoseError = (res) => {
  proxy.$modal.confirm(res.data.content[0].message, '覆盖', '不覆盖').then(() => {
    errorPublish(true)
  }).catch(err => {
    console.log('取消');
    errorPublish(false)
  });
}
const errorPublish = (newForced) => {
  product.personalproduct.personalproductPublish({
    data: {
      ...productRelease.value,
      forced: newForced
    }
  }
  ).then((res) => {
    if (res.code === 200) {
      handleBack();
      proxy.$modal.msgSuccess(res.message);
    }
  });
}

// 站点选择确定
const handleListSure = (list) => {
  dialogVisible.value = false;
  siteLength.value = list.length;
  productRelease.value.websiteIds = list;
  console.log(productRelease.value.websiteIds);
};

// 取消站点显示
const handleListClose = () => {
  dialogVisible.value = false;
};
const choseSite = () => {
  console.log(productRelease.value.websiteIds);
  dialogVisible.value = true;
};

const handleBack = () => {
  productRelease.value.websiteIds = [];
  sessionStorage.removeItem("productListIds");
  router.back();
};
// 分页
const handlePageChange = (newPage) => {
  queryParams.value.pageNum = newPage.page;
  queryParams.value.pageSize = newPage.limit;
  getList();
};
const handleImage = (row) => {
  var imageExtensionsRegex = /^https?:\/\//i;
  if (!imageExtensionsRegex.test(row.mainImage)) {
    return row.host;
  } else {
    return row.mainImage;
  }
};
</script>
